package com.example.testproject.view;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.testproject.R;
import com.example.testproject.utils.banner.ScaleTransformer;
import com.example.testproject.utils.banner.StackPageTransformer;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Package: com.example.testproject.view
 * @ClassName: BannerView
 * @Author: szj
 * @CreateDate: 8/24/21 10:26 AM
 * TODO 基于ViewPager封装的无限滚动Banner
 */
public class BannerView extends ViewPager {

    private final BannerViewAdapter bannerViewAdapter;

    //计时器
    Timer timer = new Timer();

    //计时器是否开始
    private boolean isStart;

    private final int HANDLER_WHAT_PAGE = 1;

    public static final int PAGE_TRANSFORMER_SCALE = 2;

    public static final int PAGE_TRANSFORMER_STACK_PAGE = 3;

    //UI切换线程
    Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == HANDLER_WHAT_PAGE) {
                int page = getCurrentItem() + 1;
                setCurrentItem(page);
            }
        }
    };

    private final TimerTask timerTask;


    public BannerView(@NonNull Context context) {
        this(context, null);
    }

    public BannerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        bannerViewAdapter = new BannerViewAdapter();
        setAdapter(bannerViewAdapter);

        //定时器播放ViewPager
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (isStart) {
                    mHandler.sendEmptyMessageDelayed(HANDLER_WHAT_PAGE, 0);
                }
            }
        };

        //滑动监听
        addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //滑动过程中handler停止发送
                isStart = false;
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                //滑动结束 handler继续发送
                isStart = true;

            }
        });





    }

    //开始计时器
    public void start(long time) {
        isStart = true;
        timer.schedule(timerTask, 0, time);
    }

    //暂停
    public void stop() {
        isStart = false;
    }

    //清空计时器【在onDestroy中取消】
    public void cancel() {
        timerTask.cancel();
    }

    //设置ViewPager类型 目前只有这两种类型
    // private static final int  PAGE_TRANSFORMER_SCALE = 2; [默认]
    //private static final int PAGE_TRANSFORMER_STACK_PAGE = 3;
    public void setPageType(@BannerViewIntDef int type) {
        //设置ViewPager 滑动样式
        ViewPager.PageTransformer pageTransformer;
        if (type == PAGE_TRANSFORMER_STACK_PAGE) {
            pageTransformer = new StackPageTransformer(this);
        } else {
            pageTransformer = new ScaleTransformer();
        }
       setPageTransformer(true, pageTransformer);
    }

    /**
     * 设置 网络图片Url
     * <p>
     * 参考:
     * private final ArrayList<String> mNekWorkUrls = new ArrayList<String>(){{
     * add("https://steamuserimages-a.akamaihd.net/ugc/931563623911695840/6D1C84C7FAAA6172FC16DF89A0DF824C6198DDE6/?imw=1024&imh=652&ima=fit&impolicy=Letterbox&imcolor=%23000000&letterbox=true");
     * add("");
     * add("");
     * add("");
     * }};
     */
    public void setUrls(ArrayList<String> url) {
        bannerViewAdapter.setUrls(url);
        bannerViewAdapter.notifyDataSetChanged();
    }

    /**
     * 设置 本地图片Url
     * 参考:
     * private final int[] mDrawables = new int[]{R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,};
     */
    public void setUrls(int[] url) {
        bannerViewAdapter.setUrls(url);
        bannerViewAdapter.notifyDataSetChanged();
    }


    /**
     * TODO BannerView适配器
     */
    public static class BannerViewAdapter extends PagerAdapter {

        //网络URL图片
        public ArrayList<String> mNetworkUrls;
        public int[] mLocalUrls;


        public void setUrls(ArrayList<String> networkUrls) {
            this.mNetworkUrls = networkUrls;
        }

        public void setUrls(int[] localUrls) {
            this.mLocalUrls = localUrls;
        }


        @Override
        public int getCount() {
            //因为要设置无限轮播,所以设置无限和
            return Integer.MAX_VALUE;
        }

        //子View显示
        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;// 过滤和缓存的作用
        }

        @NotNull
        @Override
        public Object instantiateItem(final ViewGroup container, final int position) {//子View显示
            View view = View.inflate(container.getContext(), R.layout.banner_item_layout, null);
            ImageView imageView = view.findViewById(R.id.iv_icon);

            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.error)//图片加载出来前，显示的图片
                    .fallback(R.mipmap.error) //url为空的时候,显示的图片
                    .error(R.mipmap.error);//图片加载失败后，显示的图片

            Object item;
            if (mNetworkUrls == null) {
                item = mLocalUrls[position % mLocalUrls.length];
            } else {
                item = mNetworkUrls.get(position % mNetworkUrls.size());
            }

            Glide.with(container.getContext())
                    .load(item)
                    .apply(options)
                    .into(imageView);

            imageView.setOnClickListener(view1 -> {
                int index;
                if (mNetworkUrls == null) {
                    index = position % mLocalUrls.length;
                } else {
                    index = position % mNetworkUrls.size();
                }

                if (mOnBannerItemClick != null) {
                    mOnBannerItemClick.onClick(view1, index);
                }
            });

            container.addView(view);//添加到父控件
            return view;
        }

        //必须重写否则: java.lang.UnsupportedOperationException: Required method destroyItem was not overridden
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//        super.destroyItem(container, position, object);这里调用了...
            container.removeView((View) object);
        }
    }


    /**
     * TODO BannerView监听
     */
    public interface OnBannerItemClick {
        /**
         * 点击View
         *
         * @param view     当前View
         * @param position 下标
         */
        void onClick(View view, int position);
    }

    public static OnBannerItemClick mOnBannerItemClick;

    public void setOnBannerItemClick(OnBannerItemClick mOnBannerItemClick) {
        this.mOnBannerItemClick = mOnBannerItemClick;
    }


    @IntDef({PAGE_TRANSFORMER_SCALE, PAGE_TRANSFORMER_STACK_PAGE})
    public @interface BannerViewIntDef {
    }
}
